/*
 * Copyright (C), 2014-2015, 杭州小卡科技有限公司
 * Created by ciwei@xiaokakeji.com on 2016/06/25.
 */
package com.micromall.task;

import com.micromall.repository.CommissionRecordMapper;
import com.micromall.repository.OrderMapper;
import com.micromall.repository.entity.CommissionRecord;
import com.micromall.repository.entity.Member;
import com.micromall.repository.entity.Order;
import com.micromall.repository.entity.common.SettleStatus;
import com.micromall.service.CashAccountService;
import com.micromall.service.MemberService;
import com.micromall.service.TransactionalExecuteService;
import com.micromall.utils.CommonEnvConstants;
import com.micromall.utils.Scale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author ciwei@xiaokakeji.com
 * @date 2016/06/25.
 */
@Component
public class CommissionSettleTask {

	private static Logger logger = LoggerFactory.getLogger(CommissionSettleTask.class);
	@Resource
	private MemberService               memberService;
	@Resource
	private OrderMapper                 orderMapper;
	@Resource
	private CommissionRecordMapper      commissionRecordMapper;
	@Resource
	private CashAccountService          cashAccountService;
	@Resource
	private TransactionalExecuteService transactionalExecuteService;

	@Scheduled(cron = "0 0/5 * * * ?")
	public void execute() {
		// 已确认收货超过7天的订单可以结算佣金
		List<Order> orders = orderMapper.findSettleOrders(CommonEnvConstants.ORDER_COMMISSION_SETTLE_TIME, new Date());
		logger.info("开始订单佣金结算任务，共有{}笔订单需要结算佣金", orders.size());
		for (Order order : orders) {
			transactionalExecuteService.execute(() -> {
				int uid = order.getUid();
				String orderNo = order.getOrderNo();
				BigDecimal orderAmount = order.getTotalAmount();

				Member member = memberService.get(order.getUid());
				if (member == null || member.getParentUid() == null) {
					orderMapper.updateSettleStatus(orderNo, SettleStatus.无法结算, new Date());
					return;
				}

				// 一级分销商商佣金计算
				Member lv1 = memberService.get(member.getParentUid());
				if (lv1 == null || lv1.isDeleted()) {
					orderMapper.updateSettleStatus(orderNo, SettleStatus.无法结算, new Date());
					return;
				}

				BigDecimal commission = Scale.scale(2, orderAmount.multiply(CommonEnvConstants.COMMISSION_DIVIDED_PROPORTION_LV1()));
				CommissionRecord commissionRecord = new CommissionRecord();
				commissionRecord.setUid(lv1.getId());
				commissionRecord.setLowerUid(uid);
				commissionRecord.setOrderNo(orderNo);
				commissionRecord.setOrderAmount(orderAmount);
				commissionRecord.setCommissionAmount(commission);
				commissionRecord.setCreateTime(new Date());
				commissionRecordMapper.insert(commissionRecord);
				cashAccountService.incrementCommission(lv1.getId(), commissionRecord.getCommissionAmount());
				cashAccountService.incrementTotalSales(lv1.getId(), order.getTotalAmount());

				if (lv1.getParentUid() != null) {
					// 二级分销商商佣金计算
					Member lv2 = memberService.get(lv1.getParentUid());
					if (lv2 == null || lv2.isDeleted()) {
						return;
					}
					commission = Scale.scale(2, orderAmount.multiply(CommonEnvConstants.COMMISSION_DIVIDED_PROPORTION_LV2()));
					commissionRecord = new CommissionRecord();
					commissionRecord.setUid(lv2.getId());
					commissionRecord.setLowerUid(uid);
					commissionRecord.setOrderNo(orderNo);
					commissionRecord.setOrderAmount(orderAmount);
					commissionRecord.setCommissionAmount(commission);
					commissionRecord.setCreateTime(new Date());
					commissionRecordMapper.insert(commissionRecord);
					cashAccountService.incrementCommission(lv2.getId(), commissionRecord.getCommissionAmount());
					cashAccountService.incrementTotalSales(lv2.getId(), order.getTotalAmount());
				}
				orderMapper.updateSettleStatus(orderNo, SettleStatus.已经结算, new Date());
			});

		}
	}
}
